package com.zyd.shiro.controller;

import com.github.pagehelper.PageInfo;
import com.zyd.shiro.business.enums.ResponseStatus;
import com.zyd.shiro.business.service.TermService;
import com.zyd.shiro.business.vo.TermConditionVO;
import com.zyd.shiro.framework.object.PageResult;
import com.zyd.shiro.framework.object.ResponseVO;
import com.zyd.shiro.persistence.beans.School;
import com.zyd.shiro.persistence.beans.Term;
import com.zyd.shiro.util.ResultUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/term")
public class TermController {

    @Autowired
    private TermService termService;

    @RequiresPermissions("term")
    @PostMapping("/list")
    public PageResult getAll(TermConditionVO vo) {
        PageInfo<Term> pageInfo = termService.findPageBreakByCondition(vo);
        return ResultUtil.tablePage(pageInfo);
    }

    @RequiresPermissions("term:add")
    @PostMapping(value = "/add")
    public ResponseVO add(Term term) {
        termService.insert(term);
        return ResultUtil.success("成功");
    }

    @RequiresPermissions(value = {"term:batchDelete", "term:delete"}, logical = Logical.OR)
    @PostMapping(value = "/remove")
    public ResponseVO remove(Long[] ids) {
        if (null == ids) {
            return ResultUtil.error(500, "请至少选择一条记录");
        }
        for (Long id : ids) {
            termService.removeByPrimaryKey(id);
        }
        return ResultUtil.success("成功删除 [" + ids.length + "] 个学年");
    }

    @RequiresPermissions("term:edit")
    @PostMapping("/get/{id}")
    public ResponseVO get(@PathVariable Long id) {
        return ResultUtil.success(null, this.termService.getByPrimaryKey(id));
    }

    @RequiresPermissions("term:edit")
    @PostMapping("/edit")
    public ResponseVO edit(Term term) {
        try {
            termService.updateSelective(term);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("学年修改失败！");
        }
        return ResultUtil.success(ResponseStatus.SUCCESS);
    }

    @RequiresPermissions("term:open")
    @PostMapping("/open")
    public ResponseVO open(Long id,Integer status) {
        String value = "";
        try {
            termService.updateTermStatus(id,status);
            if(status == 1){
                value = "开启";
            }else{
                value = "禁用";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("学年开启/禁用失败！");
        }
        return ResultUtil.success("成功"+ value +"学年");
    }
}
